package org.yang.loginunion.core.mobile;

import org.apache.commons.lang3.StringUtils;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.repository.VerifycodeRepository;

/**
 * 手机号+验证码登录
 *
 * @author Billyang
 * @date 2024/8/6 11:21
 */
public class MobileCodeClient implements LoginClient {

    private OauthRepository oauthRepository;
    private VerifycodeRepository verifycodeRepository;

    public MobileCodeClient(OauthRepository oauthRepository, VerifycodeRepository verifycodeRepository) {
        this.oauthRepository = oauthRepository;
        this.verifycodeRepository = verifycodeRepository;
    }


    @Override
    public String login(String mobile, String code, String ignore3) {
        if (StringUtils.isAnyBlank(mobile, code)) {
            throw new LoginException("缺失参数");
        }

        boolean checkVerifycode = verifycodeRepository.checkVerifycode(mobile, code);
        if (!checkVerifycode) {
            throw new LoginException("验证码错误");
        }

        String userId = oauthRepository.getUserId(IdentityType.MOBILE, mobile);
        if (userId == null) {
            userId = oauthRepository.registerUser(IdentityType.MOBILE, mobile);
        }
        return userId;
    }
}
